package com.crois.barrier.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crois.barrier.admin.entity.StatisticsSend;
import com.crois.barrier.admin.mapper.StatisticsSendMapper;
import com.crois.barrier.common.exception.BarrierException;
import com.crois.barrier.common.exception.BarrierExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 17:42 2021/11/4
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class StatisticsSendSvc extends ServiceImpl<StatisticsSendMapper,StatisticsSend> implements IStatisticsSendSvc {


    @Override
    public List<StatisticsSend> findStatisticsSendList() {
        return baseMapper.selectList(null);
    }

    @Override
    public void addStatisticsSend(StatisticsSend statisticsSend) {
        QueryWrapper<StatisticsSend> statisticsSendQueryWrapper = new QueryWrapper<>();
        statisticsSendQueryWrapper.lambda().eq(StatisticsSend::getIp,statisticsSend.getIp())
                .eq(StatisticsSend::getRouteId,statisticsSend.getRouteId())
                .eq(StatisticsSend::getRequestPath,statisticsSend.getRequestPath());
        StatisticsSend statisticsSendDb = baseMapper.selectOne(statisticsSendQueryWrapper);
        int result ;
        if (Objects.isNull(statisticsSendDb)){
            statisticsSend.setNumber(1);
            result = baseMapper.insert(statisticsSend);
        }else {
            statisticsSendDb.setNumber(statisticsSendDb.getNumber()+1);
            result = baseMapper.updateById(statisticsSendDb);
        }
        if (result==0) {
           throw new BarrierException(BarrierExceptionEnum.BARRIER_GATEWAY_LOG_STATISTICS_ADD_FAIL);
        }
    }
}
